<script setup lang="ts">
  import { HModal } from '@/components/common'
  import { ref, watch } from 'vue'
  import HButton from '../../../../common/button/HButton.vue'
  import { orderArchived } from '@/api/archived'
  import { ElMessage } from 'element-plus'

  const props = defineProps<{
    modelValue: boolean
    isBatch: boolean
    selettion: Array<string>
  }>()

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update'): void
  }>()

  /**
   * 弹窗的显示状态
   */
  const visible = ref(false)

  /**
   * 关闭事件
   */
  const onClose = () => {
    visible.value = false
    form.value.remark = ''
    emits('update:modelValue', visible.value)
  }

  /**
   * 弹窗的加载
   */
  const saveLoading = ref(false)

  /**
   * 表单
   */
  const form = ref<{ remark: string; workIds: Array<string> }>({
    remark: '',
    workIds: props.selettion,
  })

  /**
   * 保存事件
   */
  const onSave = async () => {
    saveLoading.value = true
    const res = await orderArchived(form.value)
    if (res.data.isError)
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 3000,
      })
    if (res.data.success) {
      emits('update')
      onClose()
    }
    saveLoading.value = false
  }

  watch(
    props,
    (value) => {
      visible.value = value.modelValue
      form.value.workIds = value.selettion
    },
    { immediate: true },
  )
</script>

<template>
  <div>
    <HModal v-model="visible" @close="onClose" width="auto">
      <template #header>
        <h3>工单归档</h3>
      </template>
      <div v-loading="saveLoading" element-loading-text="加载中...">
        <div v-if="props.isBatch" class="title">
          <span>当前选中&nbsp;</span>
          <span class="num">{{ props.selettion.length }}</span>
          <span>&nbsp;个工单进行批量操作！</span>
        </div>
        <el-form ref="formRef" :model="form" class="form_content">
          <el-form-item label="处理备注">
            <el-input
              v-model="form.remark"
              maxlength="200"
              placeholder="请输入处理备注"
              show-word-limit
              type="textarea"
              resize="both"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onSave">保存</HButton>
        <HButton is-modal @click="onClose">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  @import './Archive.scss';
</style>
